package com.miyake.server.servlet;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class FileCache {

	private Map<String, Map<String, byte[]>> cacheFileMap = new HashMap<String, Map<String, byte[]>>();
	private String url;

	public FileCache(String url) {
		this.url = url;
	}
	public void cacheFile(HttpServletRequest req, HttpServletResponse resp) {
		try {
			ServletFileUpload upload = new ServletFileUpload();  
	    	int sizeMax = -1;
	    	upload.setSizeMax(sizeMax);
	    	upload.setFileSizeMax(sizeMax);
	    	resp.setContentType("text/plain");        
	    	FileItemIterator iterator = upload.getItemIterator(req);       

	    	Map<String, byte[]> map = new HashMap<String, byte[]>();
	    	while (iterator.hasNext()) {           
	    		FileItemStream item = iterator.next(); 
	    		
	    		InputStream stream = item.openStream();
	    		BufferedInputStream bis = new BufferedInputStream(stream);  
	    		byte[] b = new ConvertStreamToByte().convert(bis);
	    		map.put(item.getName(), b); 
	    		
	        	resp.getWriter().println(item.getName());
	        	resp.getWriter().println(b.length + "bytes");
	    	}
	    	
	    	UserService userService = UserServiceFactory.getUserService();
	    	if (req.getUserPrincipal() != null) {
				User user = userService.getCurrentUser(); 
				cacheFileMap.put(user.getEmail(), map);
		    	
				for (Map.Entry<String, Map<String, byte[]>> e : cacheFileMap.entrySet()) {
					resp.getWriter().println(e.getKey() + "<br>");
					for (Map.Entry<String, byte[]> e2 : e.getValue().entrySet()) {
						resp.getWriter().println(e2.getValue().length + "bytes");
					}
				}
	    	}
	    	else {
				resp.getWriter().println("<a href=\"" + userService.createLoginURL(
						this.url) + "\">login</a>");
	    	}
			resp.getWriter().flush();
			resp.getWriter().close();
	    } catch (Exception ex) {       
//	    	resp.getWriter().print(ex.toString());
//	    	resp.getWriter().close();
	    }

	}
	
	public void createListPage(HttpServletRequest req, HttpServletResponse resp) {
		try {
			resp.setContentType("text/html");
			resp.getWriter().println("GET:Hello ");

			if (req.getUserPrincipal() != null) {
				UserService userService = UserServiceFactory.getUserService();
				User user = userService.getCurrentUser();  
				resp.getWriter().println(user.getNickname());
				resp.getWriter().println();
			}
			else {
				UserService userService = UserServiceFactory.getUserService();
				resp.getWriter().println("<a href=\"" + userService.createLoginURL(
						this.url) + "\">login</a>");
			}
	
			resp.getWriter().println("files:" + cacheFileMap.size());
			for (Map.Entry<String, Map<String, byte[]>> e : cacheFileMap.entrySet()) {
				resp.getWriter().println(e.getKey() + "<br>");
				for (Map.Entry<String, byte[]> e2 : e.getValue().entrySet()) {
					resp.getWriter().print("<a href=\"/fileServlet/" + e2.getKey() + "?download=" + e2.getKey() + "\">" + e2.getKey() + " (" + e2.getValue().length + "bytes)" + "</a><br>");
				}
			}
			
			resp.getWriter().flush();
			resp.getWriter().close();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	protected void downloadFile(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {
		try {
			UserService userService = UserServiceFactory.getUserService();
			if (req.getUserPrincipal() != null) {
				User user = userService.getCurrentUser();
				Map<String, byte[]> map = cacheFileMap.get(user.getEmail());
				String filename = req.getParameter("download");
				byte[] b = map.get(filename);
				resp.setContentType("application/octet-stream");
				resp.setHeader("Content-disposition", "attachment; filename=" + filename);
		
				map.remove(filename);
				resp.getOutputStream().write(b);
				resp.getOutputStream().flush();
				resp.getOutputStream().close();
			}
			else {
				resp.getWriter().println("<a href=\"" + userService.createLoginURL(
						this.url) + "\">login</a>");	
				resp.getWriter().flush();
				resp.getWriter().close();
			}
		}
		catch (Exception e) {
			e.printStackTrace(resp.getWriter());
		}
	}
	
	public Map<String, byte[]> getFileList() {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser(); 
    	if (user != null) {
    		return this.cacheFileMap.get(user.getEmail());
    	}
    	return null;
	}
}
